package com.css.fxfzdzzh.zcpt.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.constants.FxfzConstants;
import com.css.fxfzdzzh.util.BuildUrl;
import com.css.fxfzdzzh.util.CreateGson;
import com.css.fxfzdzzh.zcpt.sys.entity.ReturnAreaTree;
import com.css.fxfzdzzh.zcpt.sys.entity.SOrg;
import com.css.fxfzdzzh.zcpt.sys.service.SysOrgService;
import com.css.fxfzdzzh.util.RestTemplateUtil;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysOrgServiceImpl implements SysOrgService {

    @Autowired
    private  RestTemplateUtil restTemplateUtil;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public String jsonSOrgToDeptTree(String orgId) {
        //读取配置文件
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String sysId = configGroup.getProperty("app.system.id");
        String url = configGroup.getProperty("baseRestUrl") + "/sorg_dzj/getOrgDeptTree?id="+orgId;
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("id",orgId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return  responseEntity.getBody();
    }

    @Override
    public List listOrgTree(String orgId) {
        List trees = null;
        String jsonStr =(String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgList");
        if(StringUtils.isNotBlank(jsonStr)){
            trees=  CreateGson.createGson().fromJson(jsonStr,List.class);
            return trees;
        }
        //读取配置文件
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String sysId = configGroup.getProperty("app.system.id");
        String url = configGroup.getProperty("baseRestUrl") + "/sorg_dzj/listAllOrgTree?pid="+orgId;
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("pid",orgId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        String body = responseEntity.getBody();
        List<JSONObject> jsonObjects = JSONObject.parseArray(body, JSONObject.class);
        Map<String,String> orgMap = new HashMap<>(jsonObjects.size());
        if(jsonObjects.size()>0){
            jsonObjects.forEach(json ->{
                orgMap.put(json.getString("id"),json.getString("name"));
            });
        }
        if(orgMap.size()>0){
            redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY + "orgMap",CreateGson.createGson().toJson(orgMap));
        }
        redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY + "orgList",body);
        return trees;
    }
//
//    private List<ReturnAreaTree> buildOrgTree(String body){
//        Gson gson = CreateGson.createGson();
//        JsonArray jsonArray = new JsonParser().parse(body).getAsJsonArray();
//        List<ReturnAreaTree> orgTrees = new ArrayList<>();
//        List<ReturnAreaTree> provinceList = new ArrayList<>();
//        //用于暂存目录级别的信息
//        ReturnAreaTree parentReturnAreaTree = null;
//        //存储加固工程信息采集机构
//        ReturnAreaTree jgReturnAreaTree = null;
//        //存储震防中心
//        ReturnAreaTree zfReturnAreaTree = null;
//        List<ReturnAreaTree> zfChildren = new ArrayList<>();
//        //存储一级、二级目录下的子机构
//        List<ReturnAreaTree> children = new ArrayList<>();
//        String parentId = "";
//        String zfzx = "";
//        for (JsonElement jsonElement : jsonArray) {
//            ReturnAreaTree returnAreaTree = gson.fromJson(jsonElement.toString(), ReturnAreaTree.class);
//            if("震防中心".equals(returnAreaTree.getName())){
//                zfzx = returnAreaTree.getId();
//            }
//            if(returnAreaTree.getParent()){
//                if (parentReturnAreaTree == null) {
//                    parentReturnAreaTree = returnAreaTree;
//                }else{
//                    if(!returnAreaTree.getId().equals(parentReturnAreaTree.getId())){
//                        if("加固工程信息采集机构".equals(parentReturnAreaTree.getName())){
//                            jgReturnAreaTree = parentReturnAreaTree;
//                            parentReturnAreaTree = returnAreaTree;
//                            continue;
//                        }
//                        if(zfzx.equals(returnAreaTree.getPid())){
//                            zfReturnAreaTree = returnAreaTree;
//                            continue;
//                        }
//                        parentReturnAreaTree.setChildren(children);
//                        if((parentReturnAreaTree.getName().equals("北京市")
//                                || parentReturnAreaTree.getName().equals("上海市")
//                                || parentReturnAreaTree.getName().equals("重庆市")
//                                || parentReturnAreaTree.getName().equals("天津市")
//                                || parentReturnAreaTree.getName().contains("省")
//                                || parentReturnAreaTree.getName().contains("自治区")
//                                || parentReturnAreaTree.getName().equals("新疆生产建设兵团"))
//                                && parentReturnAreaTree.getParent()){
//                            //加各个省会
//                            provinceList.add(parentReturnAreaTree);
//                        }
//                        if("震防中心".equals(parentReturnAreaTree.getName())){
//                            //加震防和加固两个大的目录
//                            orgTrees.add(parentReturnAreaTree);
//                        }
//                        parentReturnAreaTree = returnAreaTree;
//                        children = new ArrayList<>();
//                    }
//                }
//                continue;
//            }
//            //是子菜单
//            if(returnAreaTree.getLeaf()){
//                if(zfReturnAreaTree!=null){
//                    if (zfReturnAreaTree.getId().equals(returnAreaTree.getPid())) {
//                        zfChildren.add(returnAreaTree);
//                    }
//                }
//                if (parentReturnAreaTree.getId().equals(returnAreaTree.getPid())) {
//                    if (zfReturnAreaTree != null) {
//                        zfReturnAreaTree.setChildren(zfChildren);
//                        children.add(zfReturnAreaTree);
//                        zfReturnAreaTree = null;
//                        zfChildren = null;
//                    }
//
//                    children.add(returnAreaTree);
//                }
//
//            }
//        }
//        assert jgReturnAreaTree != null;
//        jgReturnAreaTree.setChildren(provinceList);
//        orgTrees.add(jgReturnAreaTree);
//        return orgTrees;
//    }

    @Override
    public ReturnAreaTree listOrgTree1(String orgId) {
        List trees = null;
        String jsonStr =(String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgList");
        if(StringUtils.isNotBlank(jsonStr)){
            trees = CreateGson.createGson().fromJson(jsonStr, List.class);
        }
        ReturnAreaTree root = new ReturnAreaTree();
        root.setOpen(true);
        //root.setChildren(null);
        root.setParent(true);
        root.setPid("");
        root.setName("组织机构");
        root.setLeaf(false);
        root.setValue("0");
        root.setId("0");
        List<ReturnAreaTree> children1 =new ArrayList<>();
        //构建一级chindren
        for(int i=0;i<trees.size();i++){
            LinkedTreeMap map = (LinkedTreeMap) trees.get(i);
            if(map.get("pId").equals("0")){
                ReturnAreaTree root1 = new ReturnAreaTree();
                root1.setOpen(Boolean.valueOf(map.get("open").toString()));
                //root.setChildren(null);isParent
                root1.setParent(Boolean.valueOf(map.get("isParent").toString()));
                root1.setPid(map.get("pId").toString());
                root1.setName(map.get("name").toString());
                root1.setLeaf(Boolean.valueOf(map.get("isLeaf").toString()));
                root1.setValue(map.get("value").toString());
                root1.setId(map.get("id").toString());
                List<ReturnAreaTree> children2 =new ArrayList<>();
                for(int j=0;j<trees.size();j++){
                    LinkedTreeMap map1 = (LinkedTreeMap) trees.get(j);
                    if(map1.get("pId").equals(root1.getId())){
                        ReturnAreaTree root2 = new ReturnAreaTree();
                        root2.setOpen(Boolean.valueOf(map1.get("open").toString()));
                        //root.setChildren(null);isParent
                        root2.setParent(Boolean.valueOf(map1.get("isParent").toString()));
                        root2.setPid(map1.get("pId").toString());
                        root2.setName(map1.get("name").toString());
                        root2.setLeaf(Boolean.valueOf(map1.get("isLeaf").toString()));
                        root2.setValue(map1.get("value").toString());
                        root2.setId(map1.get("id").toString());
                        List<ReturnAreaTree> children3 =new ArrayList<>();
                        for (int t = 0; t < trees.size(); t++) {
                          LinkedTreeMap map2 = (LinkedTreeMap) trees.get(t);
                          if(map2.get("pId").equals(root2.getId())){
                            ReturnAreaTree root3 = new ReturnAreaTree();
                              root3.setOpen(Boolean.valueOf(map2.get("open").toString()));
                            //root.setChildren(null);isParent
                              root3.setParent(Boolean.valueOf(map2.get("isParent").toString()));
                              root3.setPid(map2.get("pId").toString());
                              root3.setName(map2.get("name").toString());
                              root3.setLeaf(Boolean.valueOf(map2.get("isLeaf").toString()));
                              root3.setValue(map2.get("value").toString());
                              root3.setId(map2.get("id").toString());
                              List<ReturnAreaTree> children4 =new ArrayList<>();
                              for (int o = 0; o < trees.size(); o++) {
                                  LinkedTreeMap map3 = (LinkedTreeMap) trees.get(o);
                                  if(map3.get("pId").equals(root3.getId())){
                                      ReturnAreaTree root4 = new ReturnAreaTree();
                                      root4.setOpen(Boolean.valueOf(map3.get("open").toString()));
                                      //root.setChildren(null);isParent
                                      root4.setParent(Boolean.valueOf(map3.get("isParent").toString()));
                                      root4.setPid(map3.get("pId").toString());
                                      root4.setName(map3.get("name").toString());
                                      root4.setLeaf(Boolean.valueOf(map3.get("isLeaf").toString()));
                                      root4.setValue(map3.get("value").toString());
                                      root4.setId(map3.get("id").toString());
                                      children4.add(root4);
                                  }
                              }
                              root3.setChildren(children4);
                              children3.add(root3);
                          }
                        }
                        root2.setChildren(children3);
                        children2.add(root2);
                    }
                }
                root1.setChildren(children2);
                children1.add(root1);
            }
        }
        if(children1.size()>0){
            root.setChildren(children1);
        }else{
            root.setChildren(new ArrayList<>(0));
        }

        return root;
    }

    @Override
    public String getOrgById(String orgId) {
        String url = BuildUrl.buildUrl() + "/sorg_dzj/getOrgById?orgId="+orgId;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("orgId",orgId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        String body = responseEntity.getBody();
        return CreateGson.createGson().toJson(buildReturnAreaTree(body));

    }

    @Override
    public String getOrgByName(String orgName) {
        String url = BuildUrl.buildUrl() + "/sorg_dzj/getOrgByName?orgName="+orgName;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("orgName",orgName);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        String body = responseEntity.getBody();
        return CreateGson.createGson().toJson(buildReturnAreaTree(body));
    }

    @Override
    public ReturnAreaTree listOrgTree2(String orgId) {
        Gson gson = CreateGson.createGson();
        String jsonStr = (String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  + "divisionTree");
        ReturnAreaTree root = gson.fromJson(jsonStr,ReturnAreaTree.class);
        if(root != null){
            return  root;
        }
        List<LinkedTreeMap> trees = null;
        jsonStr =(String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgList");
        if(StringUtils.isNotBlank(jsonStr)){
            trees = CreateGson.createGson().fromJson(jsonStr, List.class);
        }else{
            String url = BuildUrl.buildUrl() + "/sorg_dzj/listAllOrgTree?pid="+orgId;
            Map<String, Object> paramMap = new HashMap<>(2);
            paramMap.put("pid",orgId);
            ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
            String body = responseEntity.getBody();
            redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY + "orgList",body);
            trees = CreateGson.createGson().fromJson(body, List.class);
        }
        root = new ReturnAreaTree();
        root.setOpen(true);
        root.setParent(true);
        root.setPid("");
        root.setName("组织机构");
        root.setLeaf(false);
        root.setValue("0");
        root.setId("0");
        List<ReturnAreaTree> children1 =new ArrayList<>();
        List<ReturnAreaTree> reduceChildren =new ArrayList<>();
        long sqlStart = System.currentTimeMillis();
//        List orgList = gson.fromJson(getParentEqual0(), List.class);
//        if(orgList!=null && orgList.size()>0){
//            for(int i=0;i< trees.size();i++){
//                LinkedTreeMap map = (LinkedTreeMap) trees.get(i);
//                ReturnAreaTree root1 = new ReturnAreaTree();
//                root1.setOpen(Boolean.valueOf(map.get("open").toString()));
//                root1.setParent(Boolean.valueOf(map.get("isParent").toString()));
//                root1.setPid(map.get("pId").toString());
//                root1.setName(map.get("name").toString());
//                root1.setLeaf(Boolean.valueOf(map.get("isLeaf").toString()));
//                root1.setValue(map.get("value").toString());
//                root1.setId(map.get("id").toString());
//                free1(map.get("id").toString(),trees,root1,0);
//                children1.add(root1);
//            }
//        }

        for(int i=0;i< trees.size();i++){
            LinkedTreeMap map = (LinkedTreeMap) trees.get(i);
              if (map.get("pId").equals("0")) {
                ReturnAreaTree root1 = new ReturnAreaTree();
                root1.setOpen(Boolean.valueOf(map.get("open").toString()));
                root1.setParent(Boolean.valueOf(map.get("isParent").toString()));
                root1.setPid(map.get("pId").toString());
                root1.setName(map.get("name").toString());
                root1.setLeaf(Boolean.valueOf(map.get("isLeaf").toString()));
                root1.setValue(map.get("value").toString());
                root1.setId(map.get("id").toString());
                //ReturnAreaTree tree = free(map.get("id").toString(),trees,root1);
                free1(map.get("id").toString(),trees,root1,0);
                children1.add(root1);
            }
        }
        long sqlEnd = System.currentTimeMillis();
        System.out.println("时间1=" + (sqlEnd-sqlStart));
        root.setChildren(children1);
        redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY +  "divisionTree",CreateGson.createGson().toJson(root));
        return root;
    }

    ReturnAreaTree free(String flag,List trees,ReturnAreaTree root){
           List<ReturnAreaTree> children =new ArrayList<>();
           int i = 0;
           for (; i < trees.size(); i++) {
              LinkedTreeMap map = (LinkedTreeMap) trees.get(i);
               if(map.get("pId").equals(flag)){
                   ReturnAreaTree root1 = new ReturnAreaTree();
                   root1.setOpen(Boolean.valueOf(map.get("open").toString()));
                   //root.setChildren(null);isParent
                   root1.setParent(Boolean.valueOf(map.get("isParent").toString()));
                   root1.setPid(map.get("pId").toString());
                   root1.setName(map.get("name").toString());
                   root1.setLeaf(Boolean.valueOf(map.get("isLeaf").toString()));
                   root1.setValue(map.get("value").toString());
                   root1.setId(map.get("id").toString());
                   free(root1.getId(),trees,root1);
                   children.add(root1);
               }
           }
           root.setChildren(children);
           return root;
    }

    void free1(String flag,List trees,ReturnAreaTree root,int leaf){
        List<ReturnAreaTree> children =new ArrayList<>();
        for (int i =0; i < trees.size(); i++) {
            LinkedTreeMap map = (LinkedTreeMap) trees.get(i);
            String name = map.get("name").toString();
            if (map.get("name").toString().equals("凭祥市")){
                System.out.println("lll");
            }
//            if(leaf == 3 ){
//                break;
//            }
            if (map.get("pId").equals(flag)) {
                ReturnAreaTree root1 = new ReturnAreaTree();
                root1.setOpen(Boolean.valueOf(map.get("open").toString()));
              // root.setChildren(null);isParent
                root1.setParent(Boolean.valueOf(map.get("isParent").toString()));
                root1.setPid(map.get("pId").toString());
                root1.setName(map.get("name").toString());
                root1.setValue(map.get("value").toString());
                root1.setId(map.get("id").toString());
                Boolean isLeaf = Boolean.valueOf(map.get("isLeaf").toString());
                root1.setLeaf(isLeaf);
                if(isLeaf){
                    children.add(root1);
                    //leaf=2;
                }else{
                    free1(root1.getId(), trees, root1,leaf);
                    children.add(root1);
                }
            }
//            else{
//                if(leaf==2){
//                    leaf = 3;
//                }
//            }


        }
        root.setChildren(children);
    }

    //获取根节点为0的结点
    private String getParentEqual0(){
        String url = BuildUrl.buildUrl() + "/sorg_dzj/getParentEqual0";
        Map<String, Object> paramMap = new HashMap<>(0);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return  responseEntity.getBody();
    }

    @Override
    public String getOrgDataByParentId(String parentId) {
        String url = BuildUrl.buildUrl() + "/sorg_dzj/getOrgDataByParentId?parentId="+parentId;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("parentId",parentId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return  responseEntity.getBody();
    }

    private ReturnAreaTree  buildReturnAreaTree(String body){
        if("".equals(body) || body == null){
            return new ReturnAreaTree();
        }
        SOrg sOrg = CreateGson.createGson().fromJson(body, SOrg.class);
        ReturnAreaTree root1 = new ReturnAreaTree();
        root1.setPid(sOrg.getParentId());
        root1.setName(sOrg.getName());
        root1.setValue(sOrg.getUuid());
        root1.setId(sOrg.getUuid());
        return root1;
    }
}
